'use client'

import React, { useEffect } from 'react'
import { useRouter } from 'next/navigation'
import { useAuthStore } from '@/store/useAuthStore'
import MainLayout from '@/components/layout/MainLayout'
import RepositoryDetail from '@/components/repository/RepositoryDetail'

interface RepositoryPageProps {
  params: {
    slug: string[]
  }
}

const RepositoryPage = ({ params }: RepositoryPageProps) => {
  const { isAuthenticated, isLoading } = useAuthStore()
  const router = useRouter()

  // 直接使用 params 对象，避免使用 React.use() 解包
  const resolvedParams = params

  useEffect(() => {
    // 如果未认证且不在加载中，重定向到登录页面
    if (!isAuthenticated && !isLoading) {
      router.push('/login')
    }
  }, [isAuthenticated, isLoading, router])

  // 如果未认证且不在加载中，不渲染内容
  if (!isAuthenticated && !isLoading) {
    return null
  }

  // 从URL参数中提取owner和repo
  // URL格式: /repository/owner/repo
  const [owner, repo] = params.slug

  if (!owner || !repo) {
    return (
      <MainLayout>
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
          <div
            className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative"
            role="alert">
            <strong className="font-bold">错误：</strong>
            <span className="block sm:inline">无效的仓库URL</span>
          </div>
        </div>
      </MainLayout>
    )
  }

  return (
    <MainLayout>
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {isLoading ? (
          <div className="flex justify-center items-center h-64">
            <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-green-500"></div>
          </div>
        ) : (
          <RepositoryDetail owner={owner} repo={repo} />
        )}
      </div>
    </MainLayout>
  )
}

export default RepositoryPage
